package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.mysql.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long id) {
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper();
        lqw.eq(UserInfo::getId,id);
        return userInfoMapper.selectOne(lqw);
    }

    @Override
    public Map<Long, UserInfo> findByIds(List<Long> userIds, UserInfo userInfo) {
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        //判断年龄要求是否为空
        lqw.in(UserInfo::getId, userIds);
        if (userInfo != null) {
            if (userInfo.getAge() != null) {
                lqw.lt(UserInfo::getAge, userInfo.getAge());
            }
            //判断性别是否有要求
            if (!StringUtils.isEmpty(userInfo.getGender())) {
                lqw.eq(UserInfo::getGender, userInfo.getGender());
            }
            if (!StringUtils.isEmpty(userInfo.getNickname())){
                lqw.like(UserInfo::getNickname,userInfo.getNickname());
            }
        }
        List<UserInfo> userInfos = userInfoMapper.selectList(lqw);
        //将userInfos 每一个id当做主键,id对应的数据当做key
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "id");
        return map;
    }

    @Override
    public IPage<UserInfo> findAll(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<UserInfo>(page, pagesize), null);
    }
}